package com.kaifamiao.req;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet( urlPatterns = "/file/list" ,
        initParams = @WebInitParam( name = "position" , value = "D:/upload" ))
public class FileListServlet extends HttpServlet {

    // 用来记录文件保存位置的字段
    private String position ;

    @Override
    public void init() throws ServletException {
        this.position = this.getInitParameter( "position" );
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding( "UTF-8" );
        response.setContentType( "text/html;charset=UTF-8" );

        PrintWriter out = response.getWriter();

        File dir = new File( position );
        File[] files = dir.listFiles();

        out.println( "<title>文件列表</title>" );

        out.println( "<table border='1' align='center' >" );
        out.println( "<tr>" );
        out.println( "<td>序号</td>");
        out.println( "<td>文件名</td>");
        out.println( "<td>体积</td>");
        out.println( "</tr>" );
        for (int i = 0 , n = files.length ; i < n ; i++) {
            File f = files[ i ];
            out.println( "<tr>" );
            out.println( "<td>" + ( i + 1 ) + "</td>");
            out.println( "<td>" + f.getName() + "</td>");
            out.println( "<td align='right'>" + f.length() + "bytes. </td>");
            out.println( "</tr>" );
        }
        out.println( "</table>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        throw new IllegalStateException( "不支持采用POST方式获取文件列表" );
    }

}
